package com.yunqiao.common.pay;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppMergePayModel;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.yunqiao.common.config.SysConfig;
import com.yunqiao.common.consts.AppConsts;
import com.yunqiao.common.exception.CustomApiException;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

public class AliPay {

    /***************************用户端***************************************/
    /**
     * appid (今日速运   用户端) 应用
     */
    public static final String ALI_APP_ID_user = "2019032363623443";
    public static final String ALI_XCX_ID_user ="2019032163618233";
    public static final String ALI_PAY_CERT_PUBLIC_KEY="/ali/alipayCertPublicKey_RSA2.crt";
    public static final String ALI_PAY_ROOT_CERT="/ali/alipayRootCert.crt";
    public static final String ALI_PAY_CERT_PUBLIC_APP="/ali/appCertPublicKey_2019032163618233.crt";
    /**
     * 应用  私匙 （用户端）
     */
    public static final String APPLICATION_PRIVATE_KEY_user = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC5A6MEyw4BEVT3\n" +
        "WWpfta3wPNXdn27jOY2YeJW3kXHP4nDrfmdY9MHwvHHB9YO+BqFm8U1BijEehj1j\n" +
        "RDZ3D0P2WqaEumx6VTIZ1wGTrzyLhb/WpgIqrjafH5gzFsJah4HjBkj1MbWeVIqw\n" +
        "Q2N0DyNS/CxDKOVO4DMfFZiq8yFlWGXDOXlT5aP5D7x4B7nnNg4LAvdxvGBSfUnu\n" +
        "IMREb7IFnKkQ0g8Rxj/i0WiVJT9RDRQiI4Hb/JfN7UrN5aUEAoOMNwsODnyFSeh7\n" +
        "1nIv+vO7T8JBg7nH+3E2mJ3q0oD+WfhRLRewGTbluDWzqxbyN8NbsMxjCtz8UkVs\n" +
        "etXFmJr3AgMBAAECggEAVBn6HbCsAgI97F5iA3XTxpPw59iUkIfV/Mw7yoE8CjK1\n" +
        "/+aq1f4UtvkCgRe4tkXPUrs30iYeY/DDsP8N/xsaWr8kWMthik52AtcAqYCL9iRr\n" +
        "awh1ja85tyWmivq6iGp2uZteyM6672kgzjUj3VsQRKXK/RB3BF7X/jZT+smgka9S\n" +
        "Ngmzy7F0e0a2GA3yTd52+AcnvNcsnIho8kfGXWAORVkia9QsVT8WenSxjf8eT6zr\n" +
        "9bjqtu/I4m97s/K87ni0hZEwu5QIcY74SKxsDDCD+Dq5rIrTARrE19AnzaBLxix/\n" +
        "XBYfnA8lOGv4/URr1i+1xTX8duH4RP4WiQfTQTLWoQKBgQDiibTiI7I13n60oZME\n" +
        "5hrINEQ2/qg9E1zKi+3XmrIERCBhM0kvS8GYhMgi9IMpveGXfHB0lhnA4DXC0Lvm\n" +
        "78FGh+4Jjrn138NxZxO9gp4naJnRcicdVdmRC591YdlXI7bzF/qJJ6o3A5TUtHKt\n" +
        "+WXG6P41BuamDRg441o/51i3kQKBgQDRE3Nn1huOgtN+7tE35cPUbh8x+6AXWyqX\n" +
        "KePcinmqpnKh7lZ9pOer2SqsdNPsFIENchtemayRAy34V17keMOWsWoy5KD6voTy\n" +
        "DYcSROGsZJiEtIv0d3HjK6TAKfdNzdA7tTgPHIW1fukupbf5poKIpZJKzeLLEq3h\n" +
        "eV9zaMM2BwKBgHv3LVO+guv1mFKSRFie7rL13wpVKo1ZhiKUlg+w6I9rFGj8XqUS\n" +
        "CJvEtZxjP09dSBDUmNlDtk4Uo3a7MMf8FUDaa4kxYFPLIjFxXZ0L2C3qkJnLpNnp\n" +
        "u8gimxzp8bw8oAXA7mmVmhDG1e/b2xGW83n4z/sGjrr5WXLv/tgPaj3xAoGBAKJb\n" +
        "1XnkReAEblMbB/O9hLaZkbYR7j9U950N1bo0+shvm4Nuf1Hw1kuYSFBGJTAmuBUF\n" +
        "8IUlF2JBMtiwmKsZsOF8Arlk3DH782e445RnU0y5jcs4HZsJirJb+QOVU0vjMPq8\n" +
        "/ryVbKwF0vT7kgPXr3SIBzP58E28wrTeuSX5S+bPAoGBAMAQbeD+e6E2xLUviJ4f\n" +
        "LXguPN4ZFN1yr4J6+Sq8WJBkSbbS+UVkcjPDH1TERYGoPvKR6QSv50qHwdG65T/y\n" +
        "m+iECgDHv9HwWZPEULhnTLL61AD9bmIn99AW2NreL/jjRdnWUPRjGHi1+Ug7AClY\n" +
        "4MrZPwxS8f7IV2AG7HJ51fxT";
    /**
     * 支付宝小程序  用户端  私匙
     */
    public static final String ALI_XCX_PUBLIC_KEY_user="MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQD7TnNjtaGYpH31V/p/VkdLQn/4V8UgXM0rn6y45dlKQ6bYlT6gFqjHyRY1hxxJF0OTbYBLex8PJz9KrVhr7y5jCTtWIgVQqRMJc0kr+wDgb/kAIxETmCQ0vmV2Vc5+oWi0pxt4BwGdeuBgAGaMVWwWFw+sAd4hROintxEUq8MhH7aaiB4tJeYyy8ttMHL/AOXbthRXQvTXK3S6PU4Ez9OyOJMEmz8g8A9D00s0HmvcCHyFUvkpLkYfyLPDs2z1TqHMklyuFpmitH/QHRyrlMfP2DrNc/huRtSIL6C8gZMxIMFafrs0NLmmC3Go6LJX29F4OAZN3cx5zqliqcRz5oMxAgMBAAECggEBAJ5Mgn7ycII4S2d6Lb58WJhdoUKL9w41pr+t6xzlHASdrMGM8U/iNhry3dyF6RlZYCXDuibRvXTMIiAmJSaIGU4lCI1vDK4McoNnbVYY3CqEHfMqI52WHmhi7oKl9lbp0YzKHpFyyF+sgR234uDPBjC8A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
     * 支付宝公钥(用户端)
     */
    public static final String  ALI_PAY_PUBLIC_KEY_user = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApxEX+ywYY/RhA0y2WX6XJclbG5sMMEDfL+KuDV83WdKACN9Szcc9Wsv8kBiZ2gHMhAk0NFr2ATgIG1NSPiFMqEEBlHEPIlbjlEoVExlRQHJyuoihaGSzX0D1F55AfyJteg3eEDf/y2ne1dygdkupfwy/1swa1BWdK6rLhyFxS0NVALLdLeBLqm5AvkAMdlnVTXfhb0TbG50cnhVbtELvO4AzGG7XJvY9nHohYIfeeWuRg7jYWBUUBfeNz2wFjCE+i2r8JYmCCJ35UXqDm+trlLKmhFVCEbjsiXKQL3Nnqc/kwvlt89xTTt9dQBtOg3sk9O5yYWLCpaeF7+RB27EWBwIDAQAB";
    /**
     * 回调地址（用户端）
     */
    public static final String CALLBACK_URL_ALI_user = SysConfig.host+"yunqiao/api/order/alipaySuccessCallBack";

    /***************************司机端***************************************/


    /**
     * appid (今日速运   司机端)
     */
    public static final String ALI_APP_ID_driver = "2019032363638338";
    /**
     * 应用公匙  私匙 （司机端）
     */
    public static final String APPLICATION_PRIVATE_KEY_driver = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHBwhmMtCCF9gl\n" +
        "fu/E7NsdoCRvYhTd2JDmt/162cPP0q/scR29N7P7A5GaOFjWVxdNFhHEVhWhiCB1\n" +
        "NFRL9gXnvfC2xjxo2IBq3oVfBwqCBkTnrUr2A2uC5u5i7IkRukIRzKKm6hbdoh81\n" +
        "gxfVsCFGULnW3wb6PYYCrP568xOU01b0CoDsl6dnPFb9IExKhr+2PInDr/iuNHQi\n" +
        "ynUg3QCVUgoFdS1qS8pdJC0x4sKmxwBShcmnnNiCLLBkCFJunZoQGi24zU71jXQ0\n" +
        "Rd6COmgL2T1adVSsnuvf/UDtRl7gh7mbRhLPfC3F2xHZ7kur+svqsmhVr7ag8qhA\n" +
        "fKPPBsvLAgMBAAECggEAcNBPtn4/Kj6Ryk81YY5QdW58uJYD9ev31o+cIrKlB3wJ\n" +
        "NCC6FrMoVbQkKCKgWH5tOsizsXKKOFGM9GKBFb2Sg1VqyG99doCh6fHP75lyH1mm\n" +
        "XRwhTWmK21xC69ffqijFook3+RzfcSmgPxjbvchkVBMWA/HPZrDQ8VtVtCNsigJv\n" +
        "h2r9GYkoKd7OzjCqAPrqACMHEur+JneFg/H2pE+GfoJaiNPiG/ZOLCaGm9hfTaG6\n" +
        "LYD32iqs2GOlUqeG9o+uGdXj07VLWRGw0/1dEPYuYeohB/i50SctnAzObcWTHq7P\n" +
        "NR6UaVbT+j0Jz7syhMQL6QWQM40uplzPA2nLTppWYQKBgQD/OLzfq8bVpnYmNSE6\n" +
        "nY0ypkZa7juhhoApCB+2S6+YHp6YZBl5Lw+5upNDK4t34XMLpabjZrCqeMb6BWp+\n" +
        "BwjTM3IZFnssV6Bo0B1qdR532QmLhsIyETSAXZL76j28Bai0rf1hhXZtIj6tiO4j\n" +
        "DQoj5JcQwVRljZnxV1a1NRv3hwKBgQDHomwA374JHG+vhSdlWlrdLIo288Mdc1wc\n" +
        "muCXJoIKyEnqkL9HEssWUvrbSdsPhNhorQOwngVos82mVpbRIzNiNc2c/TlOJ2pC\n" +
        "113I/eXxMK9sPMRZ6v19bqlglknEX2uB04aJ7SHcMnm214pbLRPFICVeE8g2ZTg0\n" +
        "lHYvC+OSnQKBgQCsX7649oShcf8kSQf7VcOyrLih23ss2fGfRNxeO/oJrMyCskC+\n" +
        "JzngwBGL8VIOEpeoCyaPOaEiUdZZsOS+37NnKbzrEtL4HOq7P6xOZXHBkjWvJcHt\n" +
        "HM+vzwNh30/4uH28IjMa9ZAJn3JjtDLaO4lYuqAI8fo1aJDLfqiSVJ9h6wKBgHkY\n" +
        "kz8seY/5Sd5EfRND7d5ACE8xKmgQ9Az9/cJyP2ve9sdsqjqosbyG9VhTwqf1Q3ir\n" +
        "ipN2J33No6+E0tNl8ONgE6tpB3va+OA219L2AKd/ismzSr/ohX+ywteuEm0mHIaS\n" +
        "EwhTabiyfZZlxK1t+JIY39HjWg109NUgQVhkc9UZAoGAe9kCeztl3Z2WKunYtdpP\n" +
        "WTWcwMuYXgbnRAn1cxY80yDocuKujkkA1UWB6LySN/QpFH+raNeUThnPqfpzRDCp\n" +
        "USD2Q3uv5MslJWTviUHX1YCd66IuSLB1n5ufyVviMe2eSK3pgHX5rmS1ryVicJdu\n" +
        "rA7M7weWwVZQtd2b1nsbUZY=";
    /**
     * 支付宝公钥(司机端)
     */
    public static final String  ALI_PAY_PUBLIC_KEY_driver = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApxEX+ywYY/RhA0y2WX6XJclbG5sMMEDfL+KuDV83WdKACN9Szcc9Wsv8kBiZ2gHMhAk0NFr2ATgIG1NSPiFMqEEBlHEPIlbjlEoVExlRQHJyuoihaGSzX0D1F55AfyJteg3eEDf/y2ne1dygdkupfwy/1swa1BWdK6rLhyFxS0NVALLdLeBLqm5AvkAMdlnVTXfhb0TbG50cnhVbtELvO4AzGG7XJvY9nHohYIfeeWuRg7jYWBUUBfeNz2wFjCE+i2r8JYmCCJ35UXqDm+trlLKmhFVCEbjsiXKQL3Nnqc/kwvlt89xTTt9dQBtOg3sk9O5yYWLCpaeF7+RB27EWBwIDAQAB";
    /**
     * 回调地址（司机端）
     */
    public static final String CALLBACK_URL_ALI_driver = SysConfig.host+"yunqiao/api/order/alipaySuccessCallBack";

    /**
     * 获取证书路径
     * @param fileName
     * @return
     */
    public static String getPath(String fileName){
        //读取本机存放的证书文件
        ClassPathResource resource = new ClassPathResource(fileName);
        System.out.println(resource.getAbsolutePath());
        return  resource.getAbsolutePath();
    }

    /**
     * 退款
     * @param orderNumber 订单号
     * @param refundAmount 退款金额
     * @param outRequestNo  退款号
     * @param roleType  用户类型   1：用户端   2：司机端
     * @return
     * @throws AlipayApiException
     */
    public static Boolean refund(String orderNumber, String refundAmount, String outRequestNo, Integer roleType) throws AlipayApiException {
//        refundAmount = "0.01";
        if (ObjectUtil.notEqual(AppConsts.USER_ROLE_TYPE_1, roleType) && ObjectUtil.notEqual(AppConsts.USER_ROLE_TYPE_2, roleType)) {
            throw new CustomApiException("选择正确的端");
        }


        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
            roleType.equals(AppConsts.PAY_TYPE_1) ? ALI_APP_ID_user : ALI_APP_ID_driver,
            roleType.equals(AppConsts.PAY_TYPE_1) ? APPLICATION_PRIVATE_KEY_user : APPLICATION_PRIVATE_KEY_driver,
            "json",
            "UTF-8",
            roleType.equals(AppConsts.PAY_TYPE_1) ?ALI_PAY_PUBLIC_KEY_user : ALI_PAY_PUBLIC_KEY_driver,
            "RSA2");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        Map<String, Object> map = new HashMap<>();
        //订单号
        map.put("out_trade_no", orderNumber);
        //退款金额
        map.put("refund_amount", refundAmount);
        //退款 号
        map.put("out_request_no", outRequestNo);
        request.setBizContent(JSONUtil.toJsonStr(map));
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        Console.log("======================退款返回结果=====================");
        Console.log(response);
        if(response.isSuccess()){
            return true;
        }
        return false;
    }
    /**
     * 小程序退款
     * @param orderNumber 订单号
     * @param refundAmount 退款金额
     * @param outRequestNo  退款号
     * @param roleType  用户类型   1：用户端   2：司机端
     * @return
     * @throws AlipayApiException
     */
    public static Boolean XCXrefund(String orderNumber, String refundAmount, String outRequestNo, Integer roleType) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                ALI_XCX_ID_user,
                ALI_XCX_PUBLIC_KEY_user,
                "json",
                "UTF-8",
                ALI_PAY_PUBLIC_KEY_user,
                "RSA2");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        Map<String, Object> map = new HashMap<>();
        //订单号
        map.put("out_trade_no", orderNumber);
        //退款金额
        map.put("refund_amount", refundAmount);
        //退款 号
        map.put("out_request_no", outRequestNo);
        request.setBizContent(JSONUtil.toJsonStr(map));
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        Console.log("======================退款返回结果=====================");
        Console.log(response);
        if(response.isSuccess()){
            return true;
        }
        return false;
    }
    /**
     * 下单
     * @param subject 描述 标题
     * @param orderNumber  订单号
     * @param totalPrice   总金额
     * @param roleType  1：用户端， 2：司机端
     * @return
     * @throws Exception
     */
    public static String pay(String subject, String orderNumber, String totalPrice, Integer roleType) throws Exception {
//        totalPrice = "0.01";
        AlipayClient alipayClient = new DefaultAlipayClient(
            "https://openapi.alipay.com/gateway.do",
            roleType.equals(AppConsts.USER_ROLE_TYPE_1) ? AliPay.ALI_APP_ID_user : AliPay.ALI_APP_ID_driver,
            roleType.equals(AppConsts.USER_ROLE_TYPE_1) ? AliPay.APPLICATION_PRIVATE_KEY_user : AliPay.APPLICATION_PRIVATE_KEY_driver,
            "json",
            "utf-8",
            roleType.equals(AppConsts.USER_ROLE_TYPE_1) ? AliPay.ALI_PAY_PUBLIC_KEY_user : AliPay.ALI_PAY_PUBLIC_KEY_driver,
            "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setSubject(subject);
        model.setOutTradeNo(orderNumber);
        model.setTimeoutExpress("30m");
        model.setTotalAmount(totalPrice);
        model.setProductCode("PRE_AUTH");
        request.setBizModel(model);
        request.setNotifyUrl(roleType.equals(AppConsts.USER_ROLE_TYPE_1) ? AliPay.CALLBACK_URL_ALI_user : AliPay.CALLBACK_URL_ALI_driver);

        //这里和普通的接口调用不同，使用的是sdkExecute
        AlipayTradeAppPayResponse response = null;
        response = alipayClient.sdkExecute(request);
        return response.getBody();
    }

    /**
     * 小程序下单
     * @param subject 描述 标题
     * @param orderNumber  订单号
     * @param totalPrice   总金额
     * @param aliCloudOpenid  支付宝用户openId
     * @return
     * @throws Exception
     */
    public static String XcxPay(String subject, String orderNumber, String totalPrice, String aliCloudOpenid) throws Exception {
//        totalPrice = "0.01";
        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipay.com/gateway.do",
                ALI_XCX_ID_user,
                ALI_XCX_PUBLIC_KEY_user,
                "json",
                "utf-8",
                AliPay.ALI_PAY_PUBLIC_KEY_user,
                "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"" +orderNumber+ "\"," +
                "\"total_amount\":" + totalPrice + "," +
                "\"buyer_id\":\"" + aliCloudOpenid + "\"," +
                "\"subject\":\"" + subject + "\"}");
        request.setNotifyUrl(AliPay.CALLBACK_URL_ALI_user);
        //这里和普通的接口调用不同，使用的是sdkExecute
        AlipayTradeCreateResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
            System.out.println("商户订单号是:" + response.getOutTradeNo());
            System.out.println("支付宝交易号:" + response.getTradeNo());
            // 4.返回订单号和支付宝交易单号
            JSONObject json=new JSONObject();
            json.put("tradeNo",response.getTradeNo());
            json.put("outTradeNo",response.getOutTradeNo());
            return json.toJSONString();
        } else {
            System.out.println("调用失败");
            return null;
        }
    }
}
